package per.hx.bs.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import per.hx.bs.entity.WxUserDO;
import per.hx.bs.entity.sys.SysUserDO;
import per.hx.bs.service.CoreService;
import per.hx.bs.util.SpringUtils;
import per.hx.bs.utils.JWT;
import per.hx.bs.service.RedisService;

import javax.servlet.http.HttpServletRequest;

/**
 * @author HuXing
 * @date 2018/5/13  17:03
 */
@RestController
public class WxBaseController {
    private final static Logger logger = LoggerFactory.getLogger(WxBaseController.class);
    private final
    RedisService redisService;

    @Autowired
    public WxBaseController(RedisService redisService) {
        this.redisService = redisService;
    }

    protected SysUserDO getSysUser() {
        WxUserDO wxUserDO = getWxUserDO();
        System.out.println(wxUserDO);
        CoreService coreService = SpringUtils.getBean(CoreService.class);
        assert wxUserDO != null;
        SysUserDO sysUserDO = coreService.getUserDOById(wxUserDO.getUserId());
        System.out.println(sysUserDO);
        return sysUserDO;
    }

    protected String getToken() {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String loginFlag = request.getHeader("loginFlag");
        logger.info(loginFlag);
        logger.info((String) redisService.get(loginFlag));
        return loginFlag;
    }

    protected Long userId() {
        String jwt = (String) redisService.get(getToken());
        WxUserDO wxUserDO = JWT.unsign(jwt, WxUserDO.class);
        return wxUserDO != null ? wxUserDO.getUserId() : null;
    }

    protected WxUserDO getWxUserDO() {
        String jwt = (String) redisService.get(getToken());
        logger.info("-----------------" + jwt);
        WxUserDO wxUserDO = JWT.unsign(jwt, WxUserDO.class);
        logger.info(wxUserDO.toString());
        return wxUserDO;
    }

}
